package com.itheima.reggie.controller;

import com.itheima.reggie.common.Page;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService ;

    @RequestMapping("/employee/login")
    @ResponseBody
    public Result<Employee> login(@RequestBody  Employee employee , HttpSession httpSession ){
        Result<Employee> login = employeeService.login(employee);
        if (login.getCode() == 1 ){
            httpSession.setAttribute("employee" , login.getData().getId() );
        }
        return login;
    }

    @RequestMapping("employee/logout")
    @ResponseBody
    public Result<Employee> logout(HttpSession httpSession){
        httpSession.invalidate();
        return Result.success(null);
    }

    @RequestMapping("/employee/page")
    @ResponseBody
    public Result<Employee> page(){
        return new Result<>();
    }


    @PostMapping("/employee")
    @ResponseBody
    public Result<Employee> add(@RequestBody  Employee employee , HttpSession httpSession ){
        employee.setCreateUser((Long)httpSession.getAttribute("employee"));
        employee.setUpdateUser((Long)httpSession.getAttribute("employee"));
        Result result = employeeService.add(employee);
        return result ;
    }

    //查询员工列表
    @GetMapping("/employee/page")
    @ResponseBody
    public Result<Page<Employee>> page(Integer page , Integer pageSize , String name ){
        Page<Employee> page1 = employeeService.page(page, pageSize, name);
        return Result.success(page1);
    }

    //修改状态
    @PutMapping("/employee")
    @ResponseBody
    public Result updateStatus( @RequestBody Employee employee, HttpSession httpSession ){
        Long employee1 = (Long) httpSession.getAttribute("employee");
        employee.setUpdateUser(employee1);
        employeeService.updateStatus(employee);
        return Result.success(null);
    }

    //员工信息回显
    @GetMapping("/employee/{id}")
    @ResponseBody
    public Result<Employee> findById( @PathVariable Long id ){
        Employee byId = employeeService.findById(id);
        return Result.success(byId);
    }

}
